<?php
/**
 * Created by PhpStorm.
 * User: robot
 * Date: 2018-04-21
 * Time: 18:33
 */

namespace app\index\controller;


use app\base\BaseController;
use think\Request;
use app\base\model\Message as MessageModel;
use think\Session;

class Message extends BaseController
{
    public function index()
    {
        return $this->fetch();
    }


    public function ajax()
    {
        $request = Request::instance();
        if (!$request->isAjax()) {
            return ['code'=>-1,'msg'=>'请求方式错误'];
        }
        $message = new MessageModel();
        $limit = $request->param('limit');
        $offset = $limit * $request->param('page')-$limit;
        $total = $message->count('messageid');
        $data = $message->limit($offset,$limit)->select();
        if($data) {
            $data = collection($data)->append(['nick'])->toArray();
        }
        return ['code' => 0, 'msg' => '', 'count' => $total, 'data' => $data];
    }



    public function submitMessage()
    {
        $request = Request::instance();
        if (!$request->has('content')) {
            return ['code' => -1, 'msg' => '请输入留言内容'];
        }

        $userid= Session::has('user') ? Session::get('user')['userid'] : false;
        if (!$userid) {
            return ['code' => -2, 'msg' => '请登录'];
        }


        $update = MessageModel::create([
            'userid' => $userid,
            'content' => $request->param('content')
        ]);

        if ($update) {
            return ['code' => 1, 'msg' => '留言成功'];
        }
        return ['code' => -1, 'msg' => '留言失败'];


    }
}